import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  Button,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  Grid,
  Typography,
  SelectChangeEvent,
} from '@mui/material';
import { addDays } from 'date-fns';
import { Product } from '../../types/product';

interface ReverseCalculationFormProps {
  products: Product[];
  initialData?: {
    productId: string;
    productName: string;
    bankName: string;
    startDate: Date;
    endDate: Date;
    principal: number;
    profit: number;
    actualRate: number;
    dailyProfit: number;
    periodDays: number;
  } | null;
  onSubmit: (data: any) => void;
  onClose: () => void;
}

const ReverseCalculationForm: React.FC<ReverseCalculationFormProps> = ({
  products,
  initialData,
  onSubmit,
  onClose,
}) => {
  const [formData, setFormData] = useState({
    productId: '',
    startDate: '',
    endDate: '',
    principal: 10000,
    profit: 0,
  });

  const [duration, setDuration] = useState<number>(0);
  const [error, setError] = useState<string>('');
  const [calculatedResults, setCalculatedResults] = useState<{
    actualRate: number;
    dailyProfit: number;
    periodDays: number;
  } | null>(null);

  useEffect(() => {
    if (initialData) {
      setFormData({
        productId: initialData.productId,
        startDate: formatDateForInput(initialData.startDate),
        endDate: formatDateForInput(initialData.endDate),
        principal: initialData.principal,
        profit: initialData.profit,
      });
    }
  }, [initialData]);

  const formatDateForInput = (date: Date): string => {
    return new Date(date).toISOString().split('T')[0];
  };

  const calculateResults = () => {
    // 验证表单
    if (!formData.productId) {
      setError('请选择理财产品');
      return;
    }

    if (!formData.startDate || !formData.endDate) {
      setError('请选择投资期限');
      return;
    }

    if (!formData.principal || formData.principal <= 0) {
      setError('请输入有效的投资金额');
      return;
    }

    if (!formData.profit || formData.profit < 0) {
      setError('请输入有效的收益金额');
      return;
    }

    const startDate = new Date(formData.startDate);
    const endDate = new Date(formData.endDate);

    if (startDate >= endDate) {
      setError('开始日期必须早于结束日期');
      return;
    }

    // 计算实际天数
    const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));

    // 计算实际年化收益率
    const actualRate = (formData.profit / formData.principal * 365 / days) * 100;

    // 计算万份收益
    const dailyProfit = (formData.profit / formData.principal * 10000) / days;

    setCalculatedResults({
      actualRate,
      dailyProfit,
      periodDays: days,
    });
  };

  const handleSubmit = () => {
    if (!calculatedResults) {
      calculateResults();
      return;
    }

    const selectedProduct = products.find(p => p.id === formData.productId);
    if (!selectedProduct) return;

    const startDate = new Date(formData.startDate);
    const endDate = new Date(formData.endDate);
    const days = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));

    onSubmit({
      productId: formData.productId,
      productName: selectedProduct.name,
      bankName: selectedProduct.bank,
      startDate: startDate,
      endDate: endDate,
      principal: formData.principal,
      profit: formData.profit,
      actualRate: calculatedResults.actualRate,
      dailyProfit: calculatedResults.dailyProfit,
      periodDays: days,
    });
  };

  return (
    <>
      <DialogTitle>
        {initialData ? '编辑收益反算' : '收益反算'}
      </DialogTitle>
      <DialogContent>
        <Box mt={2}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}

          <Grid container spacing={2}>
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>选择理财产品</InputLabel>
                <Select
                  value={formData.productId}
                  label="选择理财产品"
                  onChange={(e) => {
                    setFormData(prev => ({ ...prev, productId: e.target.value }));
                    setCalculatedResults(null);
                  }}
                >
                  {products.map((product) => (
                    <MenuItem key={product.id} value={product.id}>
                      {product.bank} - {product.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                type="date"
                label="购买日期"
                required
                value={formData.startDate}
                onChange={(e) => {
                  const newStartDate = e.target.value;
                  setFormData(prev => ({ ...prev, startDate: newStartDate }));
                  
                  // 如果已经选择了期限，自动更新结束日期
                  if (duration > 0 && newStartDate) {
                    const endDate = addDays(new Date(newStartDate), duration);
                    setFormData(prev => ({
                      ...prev,
                      startDate: newStartDate,
                      endDate: formatDateForInput(endDate)
                    }));
                  }
                  
                  setCalculatedResults(null);
                }}
                InputLabelProps={{ shrink: true }}
              />
            </Grid>

            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                type="date"
                label="结束日期"
                required
                value={formData.endDate}
                onChange={(e) => {
                  setFormData(prev => ({ ...prev, endDate: e.target.value }));
                  setDuration(0); // 手动修改日期时重置期限选择
                  setCalculatedResults(null);
                }}
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
            
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>快速选择期限</InputLabel>
                <Select
                  value={duration}
                  label="快速选择期限"
                  onChange={(e: SelectChangeEvent<number>) => {
                    const selectedDuration = Number(e.target.value);
                    setDuration(selectedDuration);
                    
                    if (selectedDuration > 0 && formData.startDate) {
                      const startDate = new Date(formData.startDate);
                      const endDate = addDays(startDate, selectedDuration);
                      setFormData(prev => ({
                        ...prev,
                        endDate: formatDateForInput(endDate)
                      }));
                      setCalculatedResults(null);
                    }
                  }}
                >
                  <MenuItem value={0}>自定义</MenuItem>
                  <MenuItem value={7}>7天</MenuItem>
                  <MenuItem value={30}>1个月</MenuItem>
                  <MenuItem value={90}>3个月</MenuItem>
                  <MenuItem value={180}>6个月</MenuItem>
                  <MenuItem value={365}>1年</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                type="number"
                label="实际投资金额"
                required
                inputProps={{ step: '0.01', min: '0' }}
                value={formData.principal}
                onChange={(e) => {
                  setFormData(prev => ({ ...prev, principal: Number(e.target.value) }));
                  setCalculatedResults(null);
                }}
              />
            </Grid>

            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                type="number"
                label="当前产生收益"
                required
                inputProps={{ step: '0.01', min: '0' }}
                value={formData.profit}
                onChange={(e) => {
                  setFormData(prev => ({ ...prev, profit: Number(e.target.value) }));
                  setCalculatedResults(null);
                }}
              />
            </Grid>
          </Grid>

          {calculatedResults && (
            <Box mt={3}>
              <Typography variant="subtitle1" gutterBottom>
                计算结果
              </Typography>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    实际年化收益率：{calculatedResults.actualRate.toFixed(2)}%
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="body1">
                    实际万份收益：{calculatedResults.dailyProfit.toFixed(2)}元
                  </Typography>
                </Grid>
              </Grid>
            </Box>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
        >
          {calculatedResults ? '保存' : '开始反算'}
        </Button>
      </DialogActions>
    </>
  );
};

export default ReverseCalculationForm;